# -*- coding: utf-8 -*-
from scpy.logger import get_logger
import os
import sys
import re
import pickle
from collections import Counter
from unified_types import *
from category_dic import category_dic

reload(sys)
sys.setdefaultencoding('utf-8')

logger = get_logger(__file__)

CURRENT_PATH = os.path.dirname(__file__)
if CURRENT_PATH:
    CURRENT_PATH = CURRENT_PATH + "/"


def search_category_type(job_text, category_key=''):
    '''
    :param job_text: 招聘的文本信息集合
    :param category_key: 招聘网站对职位自己打的标签信息
    :return:职位的精确分类
    category_dic: 分类字典
    '''
    try:
        count_dic = dict()
        if category_key in category_dic.keys():
            for category_class, classList in category_dic.get(category_key).items():
                count_dic[category_key + ':' + category_class] = 0
                for classItem in classList:
                    if len(re.findall(classItem, job_text)) != 0:
                        count_dic[category_key + ':' + category_class] += len(re.findall(classItem, job_text))
                        # print classItem
        else:
            for key in category_dic.keys():
                for category_class, classList in category_dic.get(key).items():
                    count_dic[key + ':' + category_class] = 0
                    for classItem in classList:
                        if len(re.findall(classItem, job_text)) != 0:
                            count_dic[key + ':' + category_class] += len(re.findall(classItem, job_text))
                            # print classItem
        if Counter(count_dic).most_common(1)[0][1] != 0:
            return Counter(count_dic).most_common(1)[0][0]
        else:
            return
    except Exception,e:
        logger.info('FUN[find_category_class] failed for:' + str(e))
        return


def job_info_trans(jobInfo):
    """
    :param jobInfo:
    include key:
    company_name         TEXT NOT NULL ,
    url                  TEXT NOT NULL UNIQUE,
    city                 TEXT ,
    entity               TEXT ,
    title                TEXT ,
    -- web side industry type
    industry             TEXT ,
    scale                TEXT ,
    short_name           TEXT ,
    working_years        TEXT ,
    salary               TEXT ,
    degree               TEXT ,
    category             TEXT ,
    category_type        TEXT ,
    keywords             TEXT [],
    company_id           TEXT ,
    nature               TEXT ,
    release_time         TIMESTAMP ,
    logo_url             TEXT ,
    welfare              TEXT [] ,
    description          TEXT ,
    info_source          TEXT ,
    update_time          TIMESTAMP
    :return: trans jobInfo
    """
    try:
        # --------trans salary-----------------
        salaryText = jobInfo.get('salary', '')
        try:
            _transSalary = float(salaryText)
        except:
            logger.info('salary text can not trans to float directly')
            _transSalary = trans_salary(salaryText)['after']
        _transSalary = _transSalary if _transSalary else 0
        jobInfo['salary'] = _transSalary
        # --------trans salary end------------

        # --------trans job category ---------
        title = jobInfo.get('title', '').decode()
        category = jobInfo.get('category', '').decode()
        description = jobInfo.get('description', '').decode()
        position = jobInfo.get('position', '').decode()
        # if isinstance(title,unicode):
        #     title.encode()
        _transTitleText = search_category_type(title + position, category_key=category)

        if _transTitleText:
            _transCategory = _transTitleText.split(':')[1]
            _transCategoryType = _transTitleText.split(':')[0]
        else:
            _transDescriptionText = search_category_type(description, category_key=category)
            if _transDescriptionText:
                _transCategory = _transDescriptionText.split(':')[1]
                _transCategoryType = _transDescriptionText.split(':')[0]
            else:
                _transCategory = u'其他'
                _transCategoryType = u'其他'
        if category != '':
            jobInfo['category_type'] = category
            jobInfo['category'] = _transCategory
        else:
            jobInfo['category'] = _transCategory
            jobInfo['category_type'] = _transCategoryType
        # ----------- trans category end -------

        # ---------- get keywords --------------
        keywords = jobInfo.get('keywords', [])
        welfare = jobInfo.get('welfare', [])
        _transKeyWords = keywords + welfare
        jobInfo['keywords'] = _transKeyWords
        # ---------- get keywords end ----------

        # ---------- get des keywords ----------
        _transDesKeyWords = []
        jobInfo['keywords_des'] = _transDesKeyWords
        # ---------- get des keywords end ------

        # ----------get degree info ------------
        degreeText = jobInfo.get('degree', '')
        _transDegree = trans_degree(degreeText)['after']
        _transDegree = _transDegree if _transDegree else u'不限'
        jobInfo['degree'] = _transDegree
        # ----------get degree info end --------

        # ---------- get working_years ---------
        workingYearsText = jobInfo.get('working_years', '')
        _transWorkingYears = trans_scale(workingYearsText)['after']
        _transWorkingYears = _transWorkingYears if _transWorkingYears else 0
        jobInfo['working_years'] = _transWorkingYears
        # ---------- get working_years end -----

        # ---------- get city ------------------
        cityText = jobInfo.get('city', '')
        _transProvince, _transCity = find_province_city(cityText)
        _transCity = _transCity if _transCity else ''
        jobInfo['city'] = _transCity
        # ---------- get city end --------------

        return jobInfo
    except Exception, e:
        logger.info('FUN[job_info_trans] failed for %s'%str(e))
        return jobInfo


class jobdata(object):
    '''
    对部分数据进行处理
    不返回评分，只返回处理好的数据
    '''
    def __init__(self,filter,data):
        try:
            self.filter = list(filter)
            self.data = dict(data)
            self.scale_value = 0
            self.salary_value = 0
        except Exception,e:
            logger.error('Initialization errors')
            raise ValueError

    def fill_data(self):
        # res = {}
        for key in self.filter:
            if key in self.data.keys():
                self.data[key] = self.__convert(key)
            else:
                continue
        # return res

    # convert a record in data to a real value. It is application-dependent.
    def __convert(self, key_word):

        if key_word == "_id":
            return self.data.get(key_word)
        if key_word == "company":
            return self.data.get(key_word)
        if key_word == "salary":
            return self.salary(self.data.get(key_word))
        if key_word == "entity":
            # 只记录原始分类不做处理
            return self.data.get(key_word)
        if key_word == "degree":
            return self.degree(self.data.get(key_word))
        if key_word == "scale":
            return self.scale(self.data.get(key_word))
        if key_word == "requireNum":
            return self.required_persons_num(self.data.get(key_word))
        if key_word == "workingYears":
            return self.required_workingYears(self.data.get(key_word))
        # if key_word == 'souceCity':
        #     return find_province_name_by_city_name(self.data.get(key_word))
        return self.data.get(key_word)

    def required_workingYears(self, req_workingYears):
        value = trans_scale(req_workingYears)['after']
        if value == None:
            logger.info('workingYears is None (because original is %s); return score 0'%trans_scale(req_workingYears)['before'])
            return 0
        else:
            return value

    def required_persons_num(self,req_num):
        value = trans_req_num(req_num)['after']
        if value == None:
            logger.info('required persons num is None (because original is %s); return 0'%trans_req_num(req_num)['before'])
            return 0
        else:
            return value

    def entity(self,entity_name):
        value = trans_entity(entity_name)['after']
        return value

    def scale(self,scale_comp):
        value = trans_scale(scale_comp)['after']
        scale_value = trans_scale(scale_comp)
        if value == None:
            logger.info('scale is None (because original is %s); return score 0'%trans_scale(scale_comp)['before'])
            return 0
        else:
            return value

    def salary(self, money):
        value = trans_salary(money)['after']
        self.salary_value = trans_salary(money)
        if value == None:
            logger.info('salary is None (because original is %s); return score 0'%trans_salary(money)['before'])
            return 0
        else:
            return value

    def degree(self,degree_name):
        value = trans_degree(degree_name)['after']
        if value == None:
            logger.error(value)
            return 0
        else:
            return value

def find_province_city(text):
    filename = 'resident_revised.pkl'
    pickleFile = file(CURRENT_PATH + filename,'r')
    mapping = pickle.load(pickleFile)
    pickleFile.close()
    province_dic = dict()
    city_dic = dict()
    for item in mapping['mapprovince'].keys():
        if text.find(item)!=-1:
            if mapping['mapprovince'][item] in province_dic.keys():
                province_dic[mapping['mapprovince'][item]] += 1
            else:
                province_dic[mapping['mapprovince'][item]] = 1
    if len(province_dic)>0:
        provinceName = Counter(province_dic).most_common()[0][0]
    else:
        provinceName = None
    for item in mapping['mapcity'].keys():
        if text.find(item)!=-1:
            if mapping['mapcity'][item] in city_dic.keys():
                city_dic[mapping['mapcity'][item]] += 1
            else:
                city_dic[mapping['mapcity'][item]] = 1
    if len(city_dic)>=1:
        cityName = Counter(city_dic).most_common()[0][0]
    else:
        cityName = None
    return provinceName, cityName

if __name__ == '__main__':
#     text = u"职位描述：\r\n\t\t\t\t\t\t岗位职责：1、根据需求和对用户研究的结果，\
#     分析用户的使用习惯、情感和体验需求；2.负责多终端产品的交互设计，与产品、UI、用研、技术等相关角色紧密合作，完成信息架构，操作流程设计，\
#     精细原型设计，以及交互规格说明文档的编写。　3.把握产品业务发展方向，规划产品的交互框架，设计相应的交互模型，并制定交互设计规范。　\
#     4.跟进UED工作流程，确保交互规范的落实与交互设计稿的完美实现。　任职资格：1、本科以上学历，具有2年以上互联网产品交互界面设计经历，\
#     有工业设计,计算机或心理学相关背景优先考虑；2、熟悉UED方法和工作流程；有较强的设计创新，逻辑思维，专业分析能力，能独立完成整个设计过程；\
#     3、熟练撑握HTML（HTML5）+CSS+Javascript，PS 、AI等设计软件；5、对用户模型、流程图、线框图、界面原型等交互设计方法能熟练应用；\
#     6、对互联网产品有深刻理解，喜欢体验各类互联网产品；7、良好逻辑思维及表达沟通能力，具有良好的团队合作精神；\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\n\n职能类别：\nUI设计师/顾问"
#     title = u'交互设计师交互设计师交互设计师交互设计师'
#     key = u'设计'
#     print search_category_type(text, key)
      text = u'重庆南岸区'
      text = u"""
            职位描述
            岗位职责
            1、专业人员职位，在上级的领导和监督下定期完成量化的工作要求，并能独立处理和解决所负责的任务；
            2、协助财务预算、审核、监督工作，按照公司及政府有关部门要求及时编制各种财务报表并报送相关部门；
            3、负责员工报销费用的审核、凭证的编制和登帐；
            4、对已审核的原始凭证及时填制记帐；
            5、准备、分析、核对税务相关问题；
            6、审计合同、制作帐目表格。

            任职资格
            1、财务、会计专业本科以上学历，持有会计证；
            2、两年以上金融会计工作经历者优先；
            3、良好的学习能力、独立工作能力；
            4、工作细致严谨，责任感强，良好的沟通能力、团队精神。
            """
  # provinceName, cityName = find_province_city(text)
  # print provinceName, cityName
      print search_category_type(text,u'职能')